﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Security.Principal;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.IdentityModel;
using System.IdentityModel;
using System.IdentityModel.Tokens;
using System.Web.UI.WebControls;
using Microsoft.IdentityModel.Claims;

namespace WebApp.Code
{
    public class AutoLoginModel : IHttpModule
    {

        ConfigUser user = ConfigUser.Load();

        public void Dispose()
        {

        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_SPBeginRequest);
        }

        void context_SPBeginRequest(object sender, EventArgs e)
        {
            
            Logger.Info("Begin SP Request");

            try
            {
                HttpContext context = HttpContext.Current;
                string requestedUrl = context.Request.Url.AbsoluteUri;
                IClaimsPrincipal cp = context.User as IClaimsPrincipal;

                //If claims principal is null, then user hasn't authenticated yet.
                if (cp == null)
                {
                    if (SPClaimsUtility.AuthenticateFormsUser(context.Request.Url, user.LoginName, user.Password))
                    {
                        SecurityToken token = GetSecurityToken(user.LoginName, user.Password);
                        if (token != null)
                        {
                            EstablishSessionWithToken(token);
                            Logger.Info("Login successful");
                            //context.Response.Redirect(requestedUrl);
                        }
                        else
                        {
                            Logger.Info("SecurityToken is null");
                            return;
                        }
                       
                    }
                    else
                    {
                        Logger.Info("login failed");
                        return;
                    }
                }
                

            }
            catch (Exception ex)
            {
                Logger.Error("SPHttpModel error.", ex);
            }
            Logger.Info("End SP Request");
        }

        private SecurityToken GetSecurityToken(string userName, string password)
        {
            Logger.Info("Begin GetSecurityToken");

            Logger.Info("Get Settings");

            SPIisSettings iisSettings = IisSettings;

            //Uri appliesTo = base.AppliesTo;
            Uri appliesTo = new Uri(user.SharePointUrl);
            if (string.IsNullOrEmpty(userName) ||
                string.IsNullOrEmpty(password))
                return null;


            SPFormsAuthenticationProvider authProvider = iisSettings.FormsClaimsAuthenticationProvider;
            //SPWindowsAuthenticationProvider authProvider = iisSettings.WindowsClaimsAuthenticationProvider;
            SecurityToken token = SPSecurityContext.SecurityTokenForFormsAuthentication(
                appliesTo,
                authProvider.MembershipProvider,
                authProvider.RoleProvider,
                userName,
                password);

            return token;
        }


        private void EstablishSessionWithToken(SecurityToken securityToken)
        {
            if (null == securityToken)
            {
                throw new ArgumentNullException("securityToken");
            }
            SPFederationAuthenticationModule fam = SPFederationAuthenticationModule.Current;
            if (null == fam)
            {
                throw new ArgumentException(null, "FederationAuthenticationModule");
            }
            fam.SetPrincipalAndWriteSessionToken(securityToken);
        }

        private SPIisSettings IisSettings
        {

            get
            {
                SPWebApplication webApp = null;
                try
                {
                    //WriteLog("SPContext.Current.Web.Url:-" + SPContext.Current.Web.Url);
                    webApp = SPWebApplication.Lookup(new Uri(user.SharePointUrl));
                }
                catch (Exception ex)
                {
                    Logger.Error("webAPP is null", ex);
                }
                SPIisSettings settings = webApp.IisSettings[SPUrlZone.Default];
                return settings;
            }
        }

        protected HttpContext Context
        {
            get { return HttpContext.Current; }
        }
        protected HttpRequest Request
        {
            get { return HttpContext.Current.Request; }
        }
    }
}